package com.inspectortime.webapp.inspector;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.inspectortime.domain.InspectorCompany;
import com.inspectortime.domain.type.State;
import com.inspectortime.repository.Factory;
import com.inspectortime.repository.Repository;
import com.inspectortime.util.SpringValidatorUtils;
import com.inspectortime.webapp.util.CustomStateEditor;

/**
 * Edit company
 * TODO: Add a validator
 *
 */
public class EditInspectorCompanyController extends SimpleFormController {
	
	private Repository repository;
	private Factory factory;
	
	private static Log log = LogFactory.getLog(EditInspectorCompanyController.class);
	protected void onBindAndValidate(HttpServletRequest request,
			Object command, BindException errors) throws Exception {
		SpringValidatorUtils.logValidationErrors(log, errors);
	}

	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(State.class, new CustomStateEditor());
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		String id = request.getParameter("id");
		InspectorCompany company = repository.loadInspectorCompany(id);
		return company;
	}
	
	protected Map referenceData(HttpServletRequest request) throws Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("states", State.values());
		return data;
	}
	
	
	protected ModelAndView onSubmit(HttpServletRequest request,	HttpServletResponse response, Object command, BindException errors)
		throws Exception {
		
		InspectorCompany company = (InspectorCompany) command;
		company.save();
		
		return new ModelAndView(getSuccessView(), errors.getModel());
	}
	
	
	
	public void setRepository(Repository repository) {
		this.repository = repository;
	}
	
	public void setFactory(Factory factory) {
		this.factory = factory;
	}

}
